'use client'

import { useEffect, useState } from 'react'
import { Role } from '@prisma/client'

interface RoleFormProps {
  role: Role | null
  onClose: () => void
  onSave: (roles: Role[]) => void
}

const availablePermissions = [
  { id: 'user_management', name: '用户管理' },
  { id: 'role_management', name: '角色管理' },
  { id: 'settings', name: '系统设置' },
  // 添加其他导航栏项
]

export const RoleForm: React.FC<RoleFormProps> = ({ role, onClose, onSave }) => {
  const [name, setName] = useState('')
  const [permissions, setPermissions] = useState<string[]>([])

  useEffect(() => {
    if (role) {
      setName(role.name)
      setPermissions(role.permissions || [])
    } else {
      setName('')
      setPermissions([])
    }
  }, [role])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const method = role ? 'PUT' : 'POST'
    const url = role ? `/api/roles/${role.id}` : '/api/roles'

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name, permissions }),
    })

    const updatedRole = await response.json()
    onSave(await fetch('/api/roles').then(res => res.json())) // 直接获取最新的角色列表
    onClose()
  }

  const handlePermissionChange = (permissionId: string) => {
    setPermissions(prev => {
      if (prev.includes(permissionId)) {
        return prev.filter(id => id !== permissionId)
      } else {
        return [...prev, permissionId]
      }
    })
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white p-4 rounded shadow">
      <h2 className="text-lg font-semibold text-gray-800">{role ? '编辑角色' : '添加角色'}</h2>
      <div className="mt-2">
        <label className="block text-gray-700">角色名称</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
          className="border border-gray-300 p-2 w-full rounded bg-gray-100 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>
      <div className="mt-2">
        <label className="block text-gray-700">可见导航栏</label>
        {availablePermissions.map(permission => (
          <div key={permission.id} className="flex items-center">
            <input
              type="checkbox"
              checked={permissions.includes(permission.id)}
              onChange={() => handlePermissionChange(permission.id)}
              className="mr-2"
            />
            <span>{permission.name}</span>
          </div>
        ))}
      </div>
      <button type="submit" className="mt-4 bg-blue-600 text-white p-2 rounded hover:bg-blue-700">
        {role ? '更新角色' : '添加角色'}
      </button>
      <button type="button" onClick={onClose} className="mt-4 ml-2 bg-gray-300 p-2 rounded hover:bg-gray-400">
        取消
      </button>
    </form>
  )
}